<?php declare(strict_types=1);

namespace Distributed\Event;

use Distributed\Contract\IEvent;
use Communication\TxSocketData;
use UntilDistributed\Log;
use Distributed\Group\TransGroupManage;
use Distributed\Constant;
use Exception;

/**
 * 规则参与者
 * @author mg
 */
class ActionRegXActor extends AbstractEvent implements IEvent
{
	/**
	 *
	 * {@inheritDoc}
	 * @see \Distributed\Contract\IEvent::parseEvent()
	 */
	public function parseEvent(int $fd): ?TxSocketData
	{
		
		$groupId = $this->data->transGroup->groupId;
		
		
		$socketData = & $this->data;
		
		Log::getInstance()->info("txmanage register transaction");
		try{
			//判断是否有事务
			$transStatus = TransGroupManage::getInstance()->getGroupStatus($groupId);
			
			dump($transStatus);
			
			if($transStatus != Constant::$tx_status_begin)
			{
				throw new Exception("regist actor to an error trans group",1);
			}
			$socketData->transaction->fd = $fd;
			$res = TransGroupManage::getInstance()->addTxTransaction($groupId, $socketData->transaction);
			
			dump($res);
			
			if(!$res)
			{
				throw new Exception("regist actor error",1);
			}
			//成功返回
			$response = TxSocketData::createResponse(Constant::$tx_complete_ok);
		}catch(Exception $e){
			Log::getInstance()->error($e->getMessage());
			//失败返回
			$response = TxSocketData::createResponse(Constant::$tx_complete_fail);
		}
		Log::getInstance()->info("txmanage register transaction end");
		
		return $response;
	}
}